package com.hermes.comics.data;

import android.text.TextUtils;

import java.net.URLEncoder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public abstract class Item<T extends Enum> {

  protected final Map<T, String> tags;

  private String id;

  protected Item(String id) {
    this.id = id;
    this.tags = new HashMap<T, String>();
  }

  public abstract List<String> row();

  public String urlForEdit() {
    String tuple = id + "#" + TextUtils.join("#", row());
    return Constants.UPDATE_FORM_URI + URLEncoder.encode(tuple) + "&submit=Submit";
  }

  protected String getTagValue(T tag, String defaultValue) {
    String value = tags.get(tag);
    return (value == null) ? defaultValue : value;
  }

  protected String getTagValue(T tag) {
    return getTagValue(tag, null);
  }

  public void setTag(T tag, String value) {
    if ((value != null)) {
      tags.put(tag, value.trim());
    }
  }

  public void removeTag(T tag) {
    tags.remove(tag);
  }

  public Map<T, String> getTags() {
    return tags;
  }

  public String verbose(String delim) {
    StringBuilder buffer = new StringBuilder();
    for (Map.Entry<T, String> entry : tags.entrySet()) {
      buffer.append(delim);
      buffer.append(entry.getKey().toString());
      buffer.append(": ");
      buffer.append(entry.getValue());
      buffer.append("\n");
    }
    return buffer.toString();
  }

  public Set<T> getDifferencesForTags(T[] tags, Item newItem) {
    Set<T> differences = new TreeSet<T>();
    for (T tag : tags) {
      String currentValue = getTagValue(tag, "");
      String newValue = newItem.getTagValue(tag, "");

      if (!newValue.equals(currentValue)) {
        differences.add(tag);
      }
    }
    return differences;
  }
}
